<?php

namespace app\modules\system\controllers;

use app\controllers\BaseController;
use app\services\OperationLog;
use app\utils\Utils;
use Yii;
use yii\helpers\ArrayHelper;


class OpController extends BaseController
{
    public function actionList($data = 0)
    {
        if (!$data) {
            return $this->render('list');
        }

        $request = Yii::$app->request;
        $post = Yii::$app->request->post();
        $get = Yii::$app->request->get();

        $where[] = ['operation_log.status' => 10];

        if ($search = Utils::formUnserialize(Yii::$app->request->post('searchData'))) {
            foreach ($search as $k => $v) {
                if ($v === '') {
                    continue;
                }
                switch ($k) {
                    case 'order_no':
                        $where[] = ['operation_log.id' => Utils::getNumeric($v, 'OP')];
                        break;
                    case 'remark':
                        $where[] = ['like', 'operation_log.remark', $v];
                        break;
                    case 'create_user':
                        $where[] = ['or', ['like', 'user.username', $v], ['like', 'user.realname', $v]];
                        break;
                    case 'created_at':
                        $time = explode('~', $v);
                        $where[] = ['>=', 'operation_log.created_at', strtotime(trim($time[0]))];
                        $where[] = ['<=', 'operation_log.created_at', strtotime(trim($time[1]))];
                        break;
                }
            }
        }

        $result = OperationLog::listPage($where, 'operation_log.*', 'operation_log.id DESC', $request->post('page', 1), $request->post('limit', 10), ['createUser']);
        $return = ArrayHelper::toArray($result);

        foreach ($result['data'] as $key => $val) {
            $return['data'][$key]['order_no'] = Utils::generateOrderNo('OP', $val->id);
            $return['data'][$key]['create_user'] = $val->createUser ? $val->createUser->name : '';
            $return['data'][$key]['created_at'] = date('Y-m-d H:i:s', $val->created_at);
        }
        return $this->asJson($return);
    }

    public function actionView($id)
    {
        if (!$model = OperationLog::findOne(['id' => $id, 'status' => 10])) {
            return $this->alert('未找到该操作日志');
        }

        return $this->render('view', ['model' => $model]);
    }
}
